/**
 * @author Chris
 */

/*
 to compress...
 d:
 cd TalkTalk\piecesofuk\Javascript
 java -jar D:\Programming\Javascript\yuicompressor-2.3.5\build\yuicompressor-2.3.5.jar songs.js -o songs.min.js
*/

/* BUGS
  FIXED: IE7 puts file:///p:// at the front of the album image on the loaded song snippet
*/

/* TODO
  expand album titles
  sort years
  put the tags in the control bar

*/


/*
 *

new song tags selectors

Themes: Love [ ]
  BreakingUp [ ]
        Fear [ ]

     select all/clear all

Years: 1997 [ ]

tags = []
>>> tags.push("Years")
1
>>> tags.push("Themes")
2
>>> tags
["Years", "Themes"]

>>> tags["Years"] = []
[]
>>> tags["Years"].push("1994")
1
>>> tags
["Years", "Themes"]
>>> tags["Years"]
["1994"]
>>> tags["Years"].push("2004")
2
*/

if (typeof PIECESOFUK == "undefined") {
	var PIECESOFUK = {};
}

var		POUClasses, POUCount;

PIECESOFUK.songTags = [];
PIECESOFUK.allSongTags = [];
PIECESOFUK.numSongs = 0;
PIECESOFUK.youTube = null;

PIECESOFUK.songs = function() {
	$("#songs").hide();
  if ( $("#songs").children().length ) PIECESOFUK.buildTagsFromHTML();
	else PIECESOFUK.loadSongs();
	$("#tagYearForm > span").tsort(); // sort the years into order
	$("#songs").show();
	$("#songs")
	  .css("height", $(document).height() - 50 + "px" )
	  .dialog( {title: "songs", width: $("body").width() - 20, height: $(document).height() - 40 });
	$("#ui-dialog-title-songs")
			   .prepend('<img class="infoViewTitleImg" src="Graphics/songs.png" width="16" height="16" alt="icon">')
         .parent()
				 .css("paddingLeft", "3px");

	$("#songs").parent().css("top", "34px");
	$("#tagData").dialog( {title: "song tags", beforeclose: function() {return false;}} );
	$("input[name=AndOr]").eq(0).attr("checked", "checked")
	$("input[name=AndOr]").eq(1).attr("checked", "")

	$("#numSongs").text(PIECESOFUK.numSongs);
	$(".songTagsHead").click( function() {
		$(".songTagsForm").hide();
		$(this).next().show();
		/*
		$(".songTagsForm").not( $(".songTagsForm", this) ).hide();
		$(".songTagsForm", this).toggle();
		*/
	});

	$("#songs a").click( function() {
		if ( $("#songSummary").hasClass("ui-dialog-content") ) {
		  if ($("#songSummary").dialog("isOpen")) $("#songSummary").dialog("moveToTop");
		   else $("#songSummary").dialog("open");
		}
    else $("#songSummary").dialog({width: 450, height: 300, title: "Song Summary",
							close: function() {}, focus: function() {} });
		var song = $(this).attr("href").split("#");
		$("#songSummary").load( song[0] + " #" + song[1], // loads the song html delimited by the song ID
			function() {
				$("#songSummary img").each( function() {
// IE doesn't like relative links somehow??	$(this).attr("src", $(this).attr("src").slice(3));
					var locateCDs = $(this).attr("src").search(/CDs|DVDs/);
					$(this).attr("src", $(this).attr("src").slice(locateCDs));
				});
			});

		return false;
	});

	$("#songSummary a").live("click", function() { alert("external links currently disabled"); return false;});


  $("input[name='tagSelector']").click( function() {
		var theClass = "." + $(this).parent().parent().parent().attr("id").slice(3) + "-" + $(this).attr("value")
		if ( $(this).is(":checked")) {
	  	if ($("input[name=AndOr]:checked").val() === "or") {

			  $(theClass).each(function() {
				  var thisCloud = $(this).attr("class").match(/cloud(\d)/);
			    if (thisCloud[1]<9) ++thisCloud[1];
			    var nextCloud = "cloud" + thisCloud[1];
			    $(this).removeClass(thisCloud[0]).addClass(nextCloud);
			  });
			} else {
				$("#songs a"+POUClasses).each(function() {
				  $(this).removeClass("cloud"+POUCount)
				  if ( $(this).is(theClass) ) {
				    $(this).addClass("cloud"+ (POUCount + 1));
				  } else {
				    $(this).addClass("cloud0");
				  }
			  });
			  ++POUCount;
			  POUClasses += theClass;

			}
		} else { // unchecked
	  	if ($("input[name=AndOr]:checked").val() === "or") {
			  $(theClass).each(function() {
				  var thisCloud = $(this).attr("class").match(/cloud(\d)/);
			    if (thisCloud[1]>0) --thisCloud[1];
			    var nextCloud = "cloud" + thisCloud[1];
			    $(this).removeClass(thisCloud[0]).addClass(nextCloud);
			  });
			} else {
		    $("#songs a"+POUClasses).each(function() {
		      $(this).removeClass("cloud"+( POUCount)).addClass("cloud0");
			  });
			  --POUCount;
			  POUClasses = PIECESOFUK.removeClass(POUClasses, theClass);
		    $("#songs a"+POUClasses).each(function() {
		        $(this).removeClass("cloud0").addClass("cloud" + POUCount);
			  });
			}
		}
		PIECESOFUK.songsHighlighted();
	});

	$("input[name='AndOr']").click(function(){
		POUClasses = "";
		POUCount = 0;
    $("#songs a").each(function() {
    	var thisCloud = $(this).attr("class").match(/cloud(\d)/);
			$(this).removeClass(thisCloud[0]).addClass("cloud0");
	  });
		$("input[type='checkbox']").each(function(){
			this.checked = false;
		});
		PIECESOFUK.songsHighlighted();
  }); // AndOr change
}

PIECESOFUK.buildTagsFromHTML = function() {
	$("#songs a").each( function() {
	  ++PIECESOFUK.numSongs;
		var allTags = $(this).attr("class");
		allTags = allTags.split(" ");
		PIECESOFUK.generateTags(allTags);
	});
}


PIECESOFUK.loadSongs = function() {
  $.ajax({
    type: "GET",
    url: "Data/songData.js",
    dataType: "script",
	  async: false,
    success: function(){
      for (var i in PIECESOFUK.songs) {
				++PIECESOFUK.numSongs;
	  	  var theURL = i;
		    var theInit = theURL.slice(0,1);
		    if ( theInit.match(/\d/) ) theInit = "0-9"; // ie begins with a number
				else if ( theInit == "P" || theInit == "Q") theInit = "PQ";
				else if ( theInit == "U" || theInit == "V") theInit = "UV";
				else if ( theInit == "X" || theInit == "Y" || theInit == "Z") theInit = "XYZ";
		    theURL = theURL.replace(/[?!' ()&=\-#\.]/g, "");
		    var x = theURL.indexOf(",");
		    if (x !== -1) theURL = theURL.slice(0, x);
		    theURL = "Songs/" + theInit + ".html#" + theURL;
        var a = $("<a></a>").attr({href: theURL, target: "_blank"}).text(i).addClass(PIECESOFUK.songs[i] + " cloud0");
		    var allTags = PIECESOFUK.songs[i];
//		    var fullClass = "";
		    allTags = allTags.split(" ");
				PIECESOFUK.generateTags(allTags);
		    $("#songs").append(a).append(" ");
      }
   },
    error: function(obj, msg){
      alert( "Unable to load songs database. Please try later. Error: " + msg );
    }
  });  // $.ajax
}

PIECESOFUK.generateTags = function(allTags) {
	for (var j in allTags) {
		if ( allTags[j] == "cloud0" ) continue;  // this is only for the HTML version
		if ( allTags[j].charAt(0) == "@" ) continue; // eg the @aka tags
		var aTag = allTags[j].split("-");
// strip off the "U" from the year
		if (aTag[0] === "Year") {
			if (aTag[1].slice(-1) === "U") aTag[1] = aTag[1].slice(0,4);
		}
		allTags[j] = aTag[0] + "-" + aTag[1];
		if ( $("#tag"+aTag[0]).length == 0 ) {
			var $form = $("<form/>")
				.attr("id", "tag" + aTag[0] + "Form")
				.addClass("songTagsForm");
			var $span = $("<span/>")
				.addClass("songTagsHead")
				.text(aTag[0]);
			$("<div/>")
				.attr("id", "tag" + aTag[0])
				.append($span, $form)
				.appendTo( $("#tagData"));
		}
		if ( $("#tagItem" + aTag[0] + aTag[1]).length == 0 ) {
//						$("<span/>").attr("id", "tagItem" + aTag[1]).text(aTag[1]).appendTo( $("#tag" + aTag[0]));
			var $input = $("<input>")
				.attr({
					type: "checkbox",
					name: "tagSelector",
					value: aTag[1],
					id: "tagItem" + aTag[0] + aTag[1]
				})
				.appendTo( $("#tag" + aTag[0]));
			$("<span/>")
				.text(aTag[1])
				.append($input)
				.appendTo( $("#tag" + aTag[0] + "Form"));
		}
	}
}



PIECESOFUK.removeClass = function(theClasses, aClass) {
/*
 * remove a single class from a string of classes
 *
 * eg ".JewelOther.Jewel.0304"
 * removing ".Jewel" will return
 * ".JewelOther.0304" ie it should ignore that first .Jewel
 */
//	var classArray = theClasses.match(/\.[a-zA-Z0-9]*/g);
	var classArray = theClasses.match(/\.[\w-\w]*/g);
	var newClasses = "";
	for (var i = 0; i < classArray.length; ++i) {
		if (aClass != classArray[i]) newClasses+=classArray[i];
	}
	return newClasses;
}



 PIECESOFUK.removeSubString = function(s, t) {
 /*
  **  Remove all occurrences of a token in a string
  **    s  string to be processed
  **    t  token to be removed
  **  returns new string
  **  @author url 	http://www.rgagnon.com/jsdetails/js-0042.html
  */
  var i = s.indexOf(t);
  var newString = "";
  if (i == -1) return s; // not found
  newString += s.substring(0,i) + PIECESOFUK.removeSubString(s.substring(i + t.length), t);
  return newString;
  }

 PIECESOFUK.songsHighlighted = function() {
	$("#songsHighlighted").text(PIECESOFUK.numSongs - $("#songs a.cloud0").size());
 }

PIECESOFUK.initSongs = function() {
	PIECESOFUK.menusInit();
  $("body").show();
	$(".aView, .aControl").hide();
	PIECESOFUK.songs();
	$("#controlBarLoader").html("");
}

/*
$(document).ready(function(){
  PIECESOFUK.songs();
  PIECESOFUK.bodyWidth = $("body").width();
  PIECESOFUK.bodyHeight = $(window).height();
});
*/
